package com.atguigu.gmall.scheduled.handler;

import com.alibaba.fastjson.JSON;
import com.atguigu.gmall.common.consts.GmallConsts;
import com.atguigu.gmall.scheduled.bean.CartInfo;
import com.atguigu.gmall.scheduled.mapper.CartInfoMapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.xxl.job.core.log.XxlJobLogger;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.BoundListOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@Component
public class CartJobHandler {
    @Resource
    CartInfoMapper cartInfoMapper;
    @Resource
    StringRedisTemplate stringRedisTemplate;
    //调度中心配置当前执行器 cartJobHandler任务定时执行
    //     每过6小时 同步一次购物车 redis的数据到数据库中
    @XxlJob("cartJobHandler")
    public ReturnT syncCartInfos(String param){
        //1、查询redis中异步失败的用户id的列表
        BoundListOperations<String, String> listOps = stringRedisTemplate.boundListOps(GmallConsts.CART_ASYNCFAIL_USERIDS);
        if(listOps.size()==0){
            return ReturnT.SUCCESS;
        }
        try {
            //2、如果用户id列表不为空：
            String userKey = listOps.rightPop();
            while(!StringUtils.isEmpty(userKey)){
                // 删除用户id在数据库中的数据
                cartInfoMapper.delete(Wrappers.lambdaQuery(CartInfo.class)
                    .eq(CartInfo::getUserId , userKey));
                // 使用每个用户id查询redis购物车数据
                BoundHashOperations<String, String, String> hashOps = stringRedisTemplate.boundHashOps(GmallConsts.CART_PREFIX + userKey);
                List<String> cartInfoJsons = hashOps.values();
                //获取下一个用户的id
                userKey = listOps.rightPop();
                if(CollectionUtils.isEmpty(cartInfoJsons)){
                    //用户购物车中没有数据   继续下一次循环
                    continue;
                }
                // 保存redis购物车数据到数据库中
                cartInfoJsons.forEach(cartInfoJson ->{
                    CartInfo cartInfo = JSON.parseObject(cartInfoJson, CartInfo.class);
                    cartInfoMapper.insert(cartInfo);
                });

            }

            return ReturnT.SUCCESS;
        } catch (Exception e) {
            XxlJobLogger.log("同步购物车数据失败,异常：{}",
                    ExceptionUtils.getStackTrace(e));
            return ReturnT.FAIL;
        }
    }
}
